package org.geektimes.projects.user.oauth2;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 码云的第三方oauth2 认证  
* @author : KangNing Hu
*/
public class MaYunOAuth2Authentication implements OAuth2Authentication {

	private static final String ORIGIN_NAME = "ma-yun";

	private OkHttpClient okHttpClient = new OkHttpClient();

	@Override
	public boolean support(OAuth2Configuration configuration) {
		return ORIGIN_NAME.equals(configuration.getOriginName());
	}

	@Override
	public Oauth2Token authenticated(OAuth2Configuration configuration , HttpServletRequest request , HttpServletResponse response) {
		try {
			Request okHttpRequest = new Request.Builder().url(getUrl(configuration, request)).post(RequestBody.create("{}".getBytes())).build();
			Call call = okHttpClient.newCall(okHttpRequest);
			Response execute = call.execute();
			ResponseBody body = execute.body();
			String str= body.string();
			JSONObject obj= JSONObject.parseObject(str);
			Oauth2Token oauth2Token = new Oauth2Token();
			oauth2Token.setAccessToken(obj.get("access_token").toString());
			return oauth2Token;
		}catch (Exception e){
			e.printStackTrace();
		}
		return new Oauth2Token();
	}
}
